import java.util.ArrayList;
import java.util.List;

/** This is a class for holding the various parts of what we need to create a search string.
 *  The main components are one or more search items, and one or more properties.
 *  @see SearchItem, @see SearchProperty
 */
public class SearchCriteria
{
	private String searchString;
	private List<SearchItem> searchItems;
	private List<SearchProperty> searchProperties;

	public SearchCriteria()
	{
		searchItems = new ArrayList<SearchItem>();
		searchProperties = new ArrayList<SearchProperty>();
	}
	
	public void addSearchItem(SearchItem item)
	{
		searchItems.add(item);
	}
	
	public List<SearchItem> getSearchItems()
	{
		return searchItems;
	}

	public void setSearchItems(List<SearchItem> searchItems)
	{
		this.searchItems = searchItems;
	}

	public String getSearchString()
	{
		return searchString;
	}

	public void setSearchString(String searchString)
	{
		this.searchString = searchString;
	}
	
	protected boolean isValidProperty(SearchProperty.Type type)
	{
		for(SearchItem i : searchItems)
			if(!i.isValidProperty(type))
				return false;
		
		return true;
	}
	
	public void setAllProperties(String value)
	{
		for(SearchProperty p : searchProperties)
		{
			p.setValue(value);
		}
	}
	
	public void setProperty(SearchProperty.Type type, String value)
	{
		if(isValidProperty(type))
		{
			int index = -1;
			for(int i = 0; i < searchProperties.size(); i++)
			{
				if(type == searchProperties.get(i).getType())
				{
					index = i;
					break;
				}
					
			}
			
			if(index > -1)
				searchProperties.get(index).setValue(value);
			else
				searchProperties.add(new SearchProperty(type, value));
		}
	}
	
	public List<SearchProperty> getSearchProperties()
	{
		return searchProperties;
	}

	public void setSearchProperties(List<SearchProperty> searchProperties)
	{
		this.searchProperties = searchProperties;
	}

	@Override	
	public String toString()
	{
		String classes = "";
		String properties = "";
		
		for(int i = 0; i < searchItems.size(); i++)
		{
			if(i == 0)
				classes = "(";
			
			classes += "upnp:class = " + "\"" + SearchItem.getSearchClass(searchItems.get(i).getClassType()) + "\"";
			if(i != searchItems.size() - 1)
				classes += " or ";
			else
				classes += ")";
		}
		
		for(int j = 0; j < searchProperties.size(); j++)
		{
			if(j == 0)
				properties = "(";
			
			SearchProperty p = searchProperties.get(j);
			properties += SearchProperty.getSearchPropertyName(p.getType()) + " contains " + "\"" + p.getValue() + "\"";
			if(j != searchProperties.size() - 1)
				properties += " or ";
			else
				properties += ")";
					
		}
		
		if(classes.length() == 0)
			return properties;
		
		if(properties.length() == 0)
			return classes;
		
		return classes + " and " + properties;
	}
}
